package com.java.controller;

import com.java.vo.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {

    @PostMapping(value = "/subLogin", produces = "application/json;charset=utf-8")
    public String subLogin(User user,@RequestParam(defaultValue = "false") Boolean remerberMe) {
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), user.getPassword());
        try {
            if (remerberMe){
                token.setRememberMe(true);
            }
            subject.login(token);
        } catch (AuthenticationException e) {
            return e.getMessage();
        }
        if (subject.hasRole("admin")) {
            return "有admin权限";
        }
        return "无admin权限";
    }

    @RequiresRoles("admin")  //需要具备admin角色才能访问该接口
    @RequestMapping(value = "/testRole", method = RequestMethod.GET)
    public String testRole() {
        return "testRole success";
    }

    @RequiresRoles("admin1")  //需要具备admin1角色才能访问该接口
    @RequestMapping(value = "/testRole1", method = RequestMethod.GET)
    public String testRole1() {
        return "testRole1 success";
    }
    @RequestMapping(value = "/testRole2", method = RequestMethod.GET)
    public String testRole2() {
        return "testRole2 success";
    }
    @RequestMapping(value = "/testRole3", method = RequestMethod.GET)
    public String testRole3() {
        return "testRole3 success";
    }
    @RequiresPermissions("xxx")  //需要具备xxx才能访问该接口
    @RequestMapping(value = "/testPermissions", method = RequestMethod.GET)
    public String testPermissions() {
        return "testPermissions success";
    }

    @RequestMapping(value = "/testPerms", method = RequestMethod.GET)
    public String testPerms() {
        return "testPerms success";
    }

    @RequestMapping(value = "/testPerms1", method = RequestMethod.GET)
    public String testPerms1() {
        return "testPerms1 success";
    }
}
